//接受web发送过来的返回事件
window.addEventListener("message", async function (event) {
    //处理页面响应的消息
    if (event.data.from === "web") {
        if (event.data.action == "localStorage_get") {
            await session.set("localStorage", event.data.data);
            // console.log("rev web response: " + JSON.stringify(event.data))
        }
        // console.log("rev web response: " + JSON.stringify(event.data))
    } else {
        if (!!event.data && !!event.data.from && event.data.from == 'extenstion') {

        } else {
            try {
                if (event.data.data.request.api.indexOf("meiri56") == -1) {

                    if (event.data.data.request.api && event.data.data.request.api.indexOf("FECU=") != -1) {
                        let FECU = event.data.data.request.api.split("FECU=")[1].split("&")[0]
                        await session.set("FECU", FECU);
                    }

                    let logBtn1 = $('#kc-login');
                    let logBtn2 = $("[name=login_dialog_btn_login]").filter(function () {
                        return this.innerHTML.indexOf("登录") != -1;
                    });

                    if ((!!logBtn1 && logBtn1.length > 0) || (!!logBtn2 && logBtn2.length > 0)) {
                        if (event.data.data.request.api.indexOf("/auth/public/captcha/check") != -1) {
                            let res = JSON.parse(event.data.data.response)
                            if (res['success']) {
                                await session.set("sliderCode_check", true);
                            }
                        }
                        if (event.data.data.request.api.indexOf("/captcha/get") != -1) {
                            let res = JSON.parse(event.data.data.response)
                            let img1 = res.repData.originalImageBase64
                            let img2 = res.repData.jigsawImageBase64
                            let dis = core.sliderCode({
                                img1: img1,
                                img2: img2,
                            })
                            if (!!!dis || dis == 0) {
                                document.getElementsByClassName("verify-refresh")[0].click();
                                await session.set("sliderCode_time", new Date().getTime());
                                return;
                            }
                            console.log(dis)

                            let sliderCode = await session.get("sliderCode", false);

                            //普通账号登录，验证码
                            //联合账号要另外处理
                            if (!!sliderCode) {
                                await localTimeFunction(async function () {
                                    let startOffset = document.getElementsByClassName("verifybox-bottom")[0].getBoundingClientRect().left;
                                    let width = document.getElementsByClassName("verify-img-panel")[0].getBoundingClientRect().width;
                                    if (width > 0) {
                                        dis = dis * (width / 310);
                                        document.getElementsByClassName("verify-move-block")[0].dispatchEvent(new MouseEvent('mousedown', {
                                            'bubbles': true,
                                            'cancelable': true,
                                            'clientX': startOffset
                                        }))
                                        await localTimeFunction(function () {
                                            document.getElementsByClassName("verify-move-block")[0].dispatchEvent(new MouseEvent('mousemove', {
                                                'bubbles': true,
                                                'cancelable': true,
                                                'clientX': startOffset + dis - 2
                                            }))
                                        }, 500)

                                        await localTimeFunction(function () {
                                            window.dispatchEvent(new KeyboardEvent('mouseup', {
                                                'bubbles': true,
                                                'cancelable': true
                                            }))
                                        }, 1000)

                                        if (window.location.href.indexOf('https://exiamfw.lines.coscoshipping.com/auth/realms/coscon/protocol/openid-connect/auth') != -1) {
                                            await session.set("current_step", "loginLoading");
                                            await session.set("current_step_time", new Date().getTime());
                                        }
                                        await session.set("sliderCode_time", new Date().getTime());
                                    }
                                }, 1000)
                            }
                        }
                    }
                    // console.log(event.data.data.response)
                }
            } catch (e) {
                console.log(event)
            }
        }
    }

});

function webError() {
    if (document.body.innerHTML.indexOf('云安全平台检测到您当前的访问行为存在异常') != -1) {
        return true;
    }
    return false;
}

//接受worker.js popup.js
chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
    if (request.type == 'heartBeat') {
        let pluginName = await session.get("pluginName", null);
        let hostCode = await session.get("hostCode", null);
        let serverName = await session.get("serverName", null);
        let res = core.heartBeat(pluginName, hostCode, serverName);

        await session.set("heartBeat_time", new Date().getTime())

        let tokenRunning = await session.get("TOKEN_RUNNING", false)
        let stopService = await session.get("stopService", false)
        if (!tokenRunning && !stopService && !webError()) {
            await session.set("TOKEN_RUNNING", true)
            await getAccountAndRefresh();
        }
        sendResponse(res);
    }
    if (request.type == 'reload' || request.type == 'init') {
        if (!webError()) {
            window.location.reload();
        }
    }
    if (request.type == 'getAccount') {
        await getAccountAndRefresh();
        sendResponse("getAccount");
    }
    return true;
});

//current_step = getAccountAndRefresh
async function getAccountAndRefresh() {
    let stopService = await session.get("stopService", false)
    if (stopService) {
        return;
    }
    await session.set("msg", "等待5秒")
    await localTimeFunction(async function () {
        console.log("getAccountAndRefresh: 开始获取账号")
        await session.set("msg", "开始获取账号")
        await session.set("TOKEN_RUNNING", true)
        await session.remove("account");
        await session.remove("loginStatus");
        await session.remove("hasDoneLogin");
        await session.set("current_step", "getAccountAndRefresh");
        await session.set("current_step_time", new Date().getTime());
        let last_account = await session.get("last_account", null)

        let pluginName = await session.get("pluginName", null);
        let hostCode = await session.get("hostCode", null);
        let serverName = await session.get("serverName", null);

        let hasGetAccount = await session.get("hasGetAccount", false);
        let hasGetAccount_time = await session.get("hasGetAccount_time", 0);
        if (!hasGetAccount || new Date().getTime() - hasGetAccount_time > 30000) {
            let res = core.getAccount(pluginName, hostCode, serverName);
            await session.set("hasGetAccount", true);
            await session.set("hasGetAccount_time", new Date().getTime());

            if (!!res && !!res['username']) {
                console.log("getAccountAndRefresh: 账号: " + res['username'])
                await session.set("msg", "获取账号:" + res['username'])
                if (!!last_account && last_account == res['username']) {
                    console.log("getAccountAndRefresh: 与上次账号重复: " + res['username'])
                    await session.set("msg", "与上次账号重复")
                    await localTimeFunction(async function () {
                        await getAccountAndRefresh();
                    }, 2000)
                    return;
                } else {
                    console.log("getAccountAndRefresh: refreshToken " + res['username'])
                    await session.set("msg", "开始设置新账号cookie")
                    await session.set("account", res)

                    await session.set("current_step", "refreshToken");
                    await session.set("current_step_time", new Date().getTime());
                    await session.remove("hasGetAccount");
                }
            } else {
                console.log("getAccountAndRefresh: 未获取到账号")
                await session.set("msg", "未获取到账号")
                await localTimeFunction(async function () {
                    await session.remove("hasGetAccount");
                    await getAccountAndRefresh();
                }, 2000)
            }
        }
    }, 5000)
}

setInterval(async function () {
    let current_step = await session.get("current_step", null);
    let account = await session.get("account", null)
    let done_refreshToken = await session.get("done_refreshToken", false)
    let done_refreshToken_time = await session.get("done_refreshToken_time", 0)
    let stopService = await session.get("stopService", false)
    if (current_step == "refreshToken" && !!account && (!done_refreshToken || new Date().getTime() - done_refreshToken_time > 30000) && !stopService) {
        await session.set("done_refreshToken", true);
        await session.set("done_refreshToken_time", new Date().getTime());
        await refreshToken(account);
    }
}, 3000)

//current_step = refreshToken
async function refreshToken(res) {
    let otherCache = (!!res && !!res['otherCache']) ? JSON.parse(res['otherCache']) : null;
    let apiToken = (!!res && !!res['apiToken']) ? JSON.parse(res['apiToken']) : null;
    if (!!otherCache && !!otherCache['cookies'] && !!otherCache['localStorage']
        && !!apiToken && !!apiToken['X-Auth-Token'] && apiToken['X-Auth-Token'].length > 0) {
        //再增加
        let message = {"from": "extenstion", "action": "localStorage_set", data: otherCache['localStorage']};
        window.postMessage(message, "*");
        sendMsg({action: 'setCookie', data: otherCache['cookies']})
        console.log("设置完cookie: " + res['username'])
        await session.set("msg", "重新设置完新账号cookie到浏览器域")

        await localTimeFunction(async function () {
            console.log("刷新: " + res['username'])
            await session.set("current_step", "checkLogin");
            await session.set("current_step_time", new Date().getTime());
            await session.remove("done_refreshToken");
            window.location.reload();
        }, 5000)

    } else {
        //cosco只能删除token，删除全部去切换账号，会直接封禁
        //先删除
        let message = {"from": "extenstion", "action": "localStorage_del"};
        window.postMessage(message, "*");
        sendMsg({action: 'delCookie', domain: 'synconhub.coscoshipping.com', data: ['token']})
        await session.set("msg", "otherCache为空，需要登陆，先删除当前cookie等账号信息")

        await localTimeFunction(async function () {
            console.log("没有othercache，需要登陆")
            await session.set("msg", "删除old cookie完成，准备登陆")
            await session.set("current_step", "login");
            await session.set("current_step_time", new Date().getTime());
            await session.remove("done_refreshToken");
            window.location.reload();
        }, 5000)
    }

}